/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package notebook;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import org.primefaces.context.RequestContext;
import org.primefaces.event.SelectEvent;

/**
 *
 * @author bkm
 */
@ManagedBean
@SessionScoped
public class TableNote implements Serializable{
    private List<Note> notes;
    private Note selectionNote = null;
    private List<Note> filteredNotes;
    private String newName;
    private String newNum;
    private String dialogHeader;
    private String flag;
    private boolean addOk = false;
    private boolean addEdButDis = true;
    private FacesMessage msg = null;  

    public String getDialogHeader() {
        return dialogHeader;
    }
    public void setDialogHeader(String dialogHeader) {
        this.dialogHeader = dialogHeader;
    }
    public boolean isAddEdButDis() {
        return addEdButDis;
    }
    public void setAddEdButDis(boolean addEdButDis) {
        this.addEdButDis = addEdButDis;
    }
    public String getNewName() {
        return newName;
    }
    public String getNewNum() {
        return newNum;
    }
    public void setNewName(String newName) {
        this.newName = newName;
    }
    public void setNewNum(String newNum) {
        this.newNum = newNum;
    } 
    public TableNote() {  
        notes = new ArrayList<Note>();  
        notes.add(new Note("Вася Пупкин", "+73434848484"));
        notes.add(new Note("Иванов Иван", "+73434545454"));
        notes.add(new Note("Иванов Петр", "+73434444444"));
    }   
    public List<Note> getFilteredNotes() {
        return filteredNotes;
    }
    public void setFilteredNotes(List<Note> filteredNotes) {
        this.filteredNotes = filteredNotes;
    }
    public Note getSelectionNote() {
        return selectionNote;
    }
    public void setSelectionNote(Note selectionNote) {
        this.selectionNote = selectionNote;
    }   
    public List<Note> getNotes() {
        return notes;
    }
    public void addEditNoteEsc(){
        this.newName = "";
        this.newNum = "";
    }
    public void addEditNote(ActionEvent actionEvent){
        RequestContext context = RequestContext.getCurrentInstance();
        addOk=false;
        msg = null;
        Check(newName, newNum, flag); 
        FacesContext.getCurrentInstance().addMessage(null, msg);  
        context.addCallbackParam("addOk", addOk);
    }
    
    public void rowDblSelect(SelectEvent event){
        dialogHeader = "Изменить запись";
        newName = selectionNote.getName();
        newNum = selectionNote.getNum();
        flag = "edit";
    }
    public void rowSelect(SelectEvent event){
        addEdButDis = false;
    }
    
    public void menuItemsListener(ActionEvent actionEvent){
        if (actionEvent.getComponent().getId().equals("newButton")){
            dialogHeader = "Добавить запись";
            newName = "";
            newNum = "";
            flag = "new";
        }else {
            dialogHeader = "Изменить запись";
            newName = selectionNote.getName();
            newNum = selectionNote.getNum();
            flag = "edit";
        }        
    }
    
    
    
    public void Check(String name,String num, String flag){
        if (!name.isEmpty() && !num.isEmpty()){
            if (flag.equals("new")) {
               for (int i = 0; i < notes.size(); i++) {
                    if (name.equals(notes.get(i).getName())){
                        msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Ошибка", "Запись с таким именем уже существует");
                        break; 
                    }else if(num.equals(notes.get(i).getNum())){
                        msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Ошибка", "Номер уже записан под именем "+notes.get(i).getName());
                        break; 
                    }
                }
                if (msg == null) {
                    Note newNote = new Note(name, num);
                    notes.add(newNote);
                    //Надо переделать. встроенный фильтр работает криво и не имеет достаточно инструментов
                    //selectionNote = newNote;
                    if (selectionNote == null) {
                        addEdButDis = true;
                    }
                    msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "", "Запись добавлена");
                    addOk = true;
                }
                
            }else{
                if (selectionNote.getName().equals(name) && selectionNote.getNum().equals(num)){
                    msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "", "Запись осталась без изменений");
                }else{
                    selectionNote.setName(name);
                    selectionNote.setNum(num);
                    msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "", "Запись изменена");
                }
                addEdButDis = false;
                addOk = true;
            }
        }else{
            if (name.isEmpty()) {
                msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Ошибка", "Поле \"Имя\" не может быть пустым");
            }else if (num.isEmpty()) {
                msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Ошибка", "Поле \"Телефон\" не может быть пустым");
            }
            addOk = false; 
        }
    }
    
    public void deleteNote(){
        notes.remove(selectionNote);
        addEdButDis = true;
        msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "", "Запись удалена");
        FacesContext.getCurrentInstance().addMessage(null, msg);
    }

    
    
}
